package unwdmi.listener;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import unwdmi.connector.StationConnector;
/**
 * The StationListener listens for WeatherStations that want to connect to the server
 * @author Stephan E G Veenstra
 *
 */
public class StationListener implements Runnable {

	private ServerSocket serverSocket;
	private ExecutorService executor;
	
	public StationListener(ServerSocket serverSocket, int limit){
		this.serverSocket = serverSocket;
		this.executor = Executors.newFixedThreadPool(limit);
	}
	
	@Override
	public void run() {
		System.out.println("Listening for WeatherStations to connect...");
		Socket stationSocket;
		
		while(true){
			try {
				// Listen for connecting WeatherStations
				stationSocket = serverSocket.accept();
				// Start a new thread for the connection
				executor.execute(new StationConnector(stationSocket));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
